package ucloud

import (
	"errors"

	"github.com/ucloud/ucloud-sdk-go/services/uaccount"
	"github.com/ucloud/ucloud-sdk-go/ucloud"
	"github.com/ucloud/ucloud-sdk-go/ucloud/auth"
	"github.com/ucloud/ucloud-sdk-go/ucloud/log"
)

type secret struct {
	pri string
	pub string
}

// 更新认证信息
func (s *secret) authInfoUpdate() (*authInfo, error) {
	if len(s.pri) == 0 {
		return nil, errors.New("Ucloud api PrivateKey is invalid !")
	}
	if len(s.pub) == 0 {
		return nil, errors.New("Ucloud api PublicKey is invalid !")
	}
	cfg := ucloud.NewConfig()
	cfg.LogLevel = log.PanicLevel
	credential := auth.NewCredential()
	credential.PrivateKey = s.pri
	credential.PublicKey = s.pub
	return &authInfo{
		cfg: &cfg,
		cre: &credential,
	}, nil
}

type authInfo struct {
	cfg *ucloud.Config
	cre *auth.Credential
}

type zoneInfo struct {
	ProjectId   string
	ProjectName string
	Region      string
	Zone        string
}

// 获取账号授权范围基本信息
func (uauth *authInfo) updateZone() ([]*zoneInfo, error) {
	account := uaccount.NewClient(uauth.cfg, uauth.cre)
	// 获取授权账号下的项目列表信息
	projectReq := account.NewGetProjectListRequest()
	project, err := account.GetProjectList(projectReq)
	if err != nil {
		return nil, err
	}
	// 获取授权账号下的地域信息
	regionReq := account.NewGetRegionRequest()
	region, err := account.GetRegion(regionReq)
	if err != nil {
		return nil, err
	}

	zoneInfoList := make([]*zoneInfo, 0, project.ProjectCount*len(region.Regions))
	for i := 0; i < project.ProjectCount; i++ {
		for j := 0; j < len(region.Regions); j++ {
			zone := new(zoneInfo)
			// 缓存项目列表的ID和名称
			zone.ProjectId = project.ProjectSet[i].ProjectId
			zone.ProjectName = project.ProjectSet[i].ProjectName
			// 缓存地域信息的关系
			zone.Region = region.Regions[j].Region
			zone.Zone = region.Regions[j].Zone

			zoneInfoList = append(zoneInfoList, zone)
		}
	}

	return zoneInfoList, nil
}
